import Article from '../Article'
import Loading from '../Loading'
import { useState, useEffect } from 'react'
import styles from './ArticleList.module.css'
import { BASE_URL } from '../../constants'

const ArticleList = () => {
  const [ articles, setArticles ] = useState([])
  const [ pending, setPending ] = useState(true)
  const [ error, setError ] = useState(null)

  const getData = () => {
    fetch(`${BASE_URL}/articles`)
    .then(res => res.json())
    .then(res => {
      if (res.status && res.status !== "ok") {
        throw new Error('请求失败')
      } else {
        setArticles(res)
      }
    })
    .catch(err => {
      setError(err.message)
    })
    .finally(() => {
      setPending(false)
    })
  }

  const flush = () => {
    getData()
  }

  useEffect(() => {
    getData()
  },[])
  return (
    <div className={styles.list}>
      <div className={styles.title}>文章列表</div>
      <div className={styles.header}>
        <div>序号</div>
        <div>标题</div>
        <div>分类</div>
        <div>创建时间</div>
        <div>修改时间</div>
        <div>操作</div>
      </div>
      <div className={styles.rows}>
        { pending && <Loading /> }
        { error && <div style={{textAlign: "center", fontSize: "30px"}}>{error}</div> }
        {
          !pending && articles.map(article => {
            return <Article key={article.id} {...article} flush={flush}/>
          })
        }
      </div>
    </div>
  )
}

export default ArticleList